package cn.haoran.common.utils;

import cn.haoran.common.exception.AppException;
import cn.haoran.modules.sys.entity.UploadFileEntity;
import com.github.tobato.fastdfs.domain.MateData;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.domain.ThumbImageConfig;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
@Component
public class FastDFSUtils {
    /** 支持的图片类型 */
    private static final String[] SUPPORT_IMAGE_TYPE = { "JPG", "JPEG", "PNG", "GIF", "BMP", "WBMP" };
    private static final List<String> SUPPORT_IMAGE_LIST = Arrays.asList(SUPPORT_IMAGE_TYPE);

    @Autowired
    private FastFileStorageClient storageClient;
    @Autowired
    private ThumbImageConfig thumbImageConfig;

    /**
     * 上传图片文件及缩略图
     */
    public StorePath uploadImageFile(File file, String fileExtName, Set<MateData> metaDataSet) throws FileNotFoundException {
        //上传文件
        return storageClient.uploadImageAndCrtThumbImage(new FileInputStream(file), file.length(), fileExtName, metaDataSet);
    }

    /**
     * 上传非图片文件
     */
    public StorePath uploadFile(File file, String suffix, Set<MetaData> meta) throws Exception {
        return storageClient.uploadFile(new FileInputStream(file), file.length(), suffix, null);
    }

    /**
     * 上传文件
     */
    public String uploadFile(MultipartFile file) {
        if(file == null || file.isEmpty()) {
            throw new AppException("上传文件不存在");
        }
        // 文件后缀名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        StorePath path;
        try {
            if(isSupportImage(suffix)) { // 图片
                // 上传图片并且生成缩略图
                path = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), suffix, null);
            } else {
                // 非图片文件
                path = storageClient.uploadFile(file.getInputStream(), file.getSize(), suffix, null);
            }
            return path.getPath();
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return "";
    }

    /**
     * 文件下载
     */
    public byte[] downloadFile(String group, String url, DownloadByteArray array) throws Exception {
        return storageClient.downloadFile(group, url, array);
    }

    /**
     * 打包下载
     */
    public void downloadZip(List<UploadFileEntity> fileList, String group, ZipOutputStream zip) throws Exception {
        DownloadByteArray downloadByteArray = new DownloadByteArray();
        for(UploadFileEntity entity : fileList) {
            // zipEntry例如：工程文档/测试文件夹/xxx.docx
            zip.putNextEntry(new ZipEntry(entity.getParentFolderPath() + entity.getName()));
            // 下载文件
            byte[] bytes = downloadFile(group, entity.getUrl(), downloadByteArray);
            // 写入zipOutputStream
            IOUtils.write(bytes, zip);
            zip.closeEntry();
        }
    }

    /**
     * 删除文件
     */
    public void deleteFile(String group, String path) {
        storageClient.deleteFile(group, path);
    }

//    public void downloadFile(ZipOutputStream zip) throws Exception {
//        String url = "M00/00/00/wKgA1V2d0KKAEB9FAAJi1MdFAb4930.png";
//        String url2 = "M00/00/00/wKgA1V2d0qiAe_nFAADGWkQfxd439.docx";
//        //创建流
//        //ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//        //ZipOutputStream zip = new ZipOutputStream(outputStream);
//        zip.putNextEntry(new ZipEntry("测试文件夹" + File.separator + "测试图片下载.png"));
//
//        DownloadByteArray downloadByteArray = new DownloadByteArray();
//        byte[] bytes = downloadFile("group1", url, downloadByteArray);
//        //InputStream inputStream = new ByteArrayInputStream(bytes);
//        IOUtils.write(bytes, zip);
//        zip.closeEntry();
//        zip.putNextEntry(new ZipEntry("测试文件夹" + File.separator + "测试文档下载.docx"));
//        bytes = downloadFile("group1", url2, downloadByteArray);
//        IOUtils.write(bytes, zip);
//        zip.closeEntry();
//    }

    /**
     *  创建元信息
     */
    public Set<MateData> createMetaData(MetaData meta) {
        Set<MateData> metaDataSet = new HashSet<>();
        metaDataSet.add(new MateData("author", meta.getAuthor()));
        metaDataSet.add(new MateData("oldName", meta.getOldName()));
        return metaDataSet;
    }

    /**
     * 是否是支持的图片文件
     */
    public boolean isSupportImage(String fileExtName) {
        return SUPPORT_IMAGE_LIST.contains(fileExtName.toUpperCase());
    }

    @Data
    public
    class MetaData {
        private String author;
        // 原文件名
        private String oldName;
    }
}
